<template>
	<el-form ref="passwordLoginForm" :model="passwordLoginForm" :rules="loginRules">
  
		<el-form-item prop="username">
			<el-input placeholder="用户名" prefix-icon="el-icon-user" v-model="passwordLoginForm.username" clearable>
			</el-input>
		</el-form-item>

		<el-form-item prop="password">
			<el-input placeholder="密码" prefix-icon="el-icon-key" v-model="passwordLoginForm.password" clearable show-password>
			</el-input>
		</el-form-item>
		
    <el-form-item prop="verificationCode">

			<el-row>
				<el-col :span="18">
					<el-input placeholder="验证码" prefix-icon="el-icon-key" v-model="verificationCode" clearable @keyup.enter.native="login('passwordLoginForm')">
					</el-input>
				</el-col>
				<el-col :span="6">
					<img :src="imgUrl" id="imgCode" @click="getVerify()" />
				</el-col>
			</el-row>

		</el-form-item>
		
    <el-button type="primary" @click="login('passwordLoginForm')">登录</el-button>
	</el-form>
</template>

<script>
import {
  passwordLogin,codeImage
} from '@/assets/request/api.js';
import tool from '@/assets/js/tool'
export default {
  name: "passwordLogin",
  mixins: [tool],
  data() {
    
    var checkVerificationCode = (rule, value, callback) => {
      if(this.verificationCode){
        callback();
      } else {
        callback("请输入验证码")
      }
    };

    return {
      imgUrl: '',
      passwordLoginForm: {
        username: '',
        password: '',
      },

      verificationCode: '',	  // 验证码数字
      verificationCodeId: '', // 验证码数字唯一编号

      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        verificationCode: [
          { validator: checkVerificationCode, trigger: 'blur' }
        ]
      }

    }
  },
  methods: {
    login(formName) {

      this.$refs[formName].validate((valid) => {
        if (valid) {
          
          this.passwordLoginForm.password = this.rsaEncryptByPublicKey(this.passwordLoginForm.password)
          sessionStorage.setItem('verificationCode',this.verificationCode);
          sessionStorage.setItem('verificationCodeId',this.verificationCodeId);

          passwordLogin(this.passwordLoginForm).then(res => {
            
            this.$message({
              message: '登录成功',
              type: 'success'
            });
            let tokenHead = res.data.tokenHead
            let token = res.data.token
            localStorage.setItem('token',tokenHead + token)
            
            this.$router.push("/home")

          }).catch(err => {

            this.$message({
              message: err.message,
              type: 'error'
            });

            if(err.code === 'A008') {

              // 传递回去，提示需要修改密码
              this.$emit('changePassword',true)

            } else {
              this.verificationCode = ''
              this.passwordLoginForm = {}
              this.getVerify()
            }

          })

        } 
      });
      
    },
    getVerify() {
      
      codeImage().then(res => {
        this.imgUrl = res.data.image
        this.verificationCodeId = res.data.code
      }).catch(err => {
        this.$message({
          message: err.message,
          type: 'error'
        });
      })
    }
  },
  mounted() {

    this.getVerify()
  }
  
}
</script>

<style scoped>
#imgCode{
  margin-top: 16px;
  margin-left: 5px;
}
.el-form-item{
  margin-bottom: 40px;
}
</style>
